package com.hanter.android.radlib.saf;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.ParcelFileDescriptor;

import com.hanter.android.radlib.util.AndroidUriUtils;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SafFileUtils {

    public static void createFile(File file) {
        if (file.exists()) return;

        File parent = file.getParentFile();
        if (parent == null || parent.exists() || parent.mkdirs()) {
            try {
                // 忽略创建文件结果
                //noinspection ResultOfMethodCallIgnored
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void copy(Context context, Uri fileUri, File dst) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                ParcelFileDescriptor pfd = context.getContentResolver()
                        .openFileDescriptor(fileUri, "r");
                if (pfd != null) {
                    copy(pfd.getFileDescriptor(), dst);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            String filePath = AndroidUriUtils.getRealFilePath(context, fileUri);
            File file = new File(filePath);

            try {
                copy(file, dst);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void copy(FileDescriptor src, File dst) throws IOException {
        try (InputStream in = new FileInputStream(src)) {
            try (OutputStream out = new FileOutputStream(dst)) {
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
        }
    }

    public static void copy(File src, File dst) throws IOException {
        try (InputStream in = new FileInputStream(src)) {
            try (OutputStream out = new FileOutputStream(dst)) {
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
        }
    }

    public static void deleteDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files == null) return;
            for (File file : files) {
                //noinspection ResultOfMethodCallIgnored
                file.delete();
            }
        }
    }

}
